<template>
  <div class="admin-container">
    <div class="table-container">
      <avue-crud
        ref="crudRef"
        :data="data"
        :option="option"
        :page="page"
        v-model:page="page"
        @size-change="sizeChange"
        @current-change="currentChange"
        @search-change="searchChange"
        @search-reset="searchReset"
        @on-load="onLoad"
        @row-save="onSubmit"
        @row-update="onUpdate"
        @row-del="onDelete"
        :loading="loading"
      >
        <!-- 自定义状态列 -->
        <template #status="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
        
        <!-- 自定义操作按钮 -->
        <template #menu="{ row }">
          <el-button 
            v-if="row.adminType !== 1" 
            :type="row.status === 1 ? 'warning' : 'success'" 
            size="small"
            @click="updateStatus(row)"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
        </template>

        <!-- 密码输入 -->
        <template #password="{ row, size, type }">
          <el-input 
            v-model="row.password" 
            placeholder="请输入密码" 
            :show-password="true"
            :disabled="type === 'view'"
            :size="size"
          />
        </template>
      </avue-crud>
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminPage, addAdmin, updateAdmin, deleteAdmin, updateAdminStatus } from '@/api/admin'

// 表格配置
const option = {
  align: 'center',
  menuAlign: 'center',
  searchMenuSpan: 6,
  border: true,
  index: true,
  viewBtn: true,
  editBtn: true,
  delBtn: true,
  page: true,
  pageSizes: [10, 20, 30, 50],
  paginationAlign: 'center',
  searchShowBtn: true,
  searchResetBtn: true,
  height: 'auto',
  column: [
    {
      label: '用户名',
      prop: 'username',
      search: true,
      rules: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ]
    },
    {
      label: '密码',
      prop: 'password',
      type: 'password',
      hide: true,
      viewDisplay: false,
      editDisplay: false,
      rules: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ],
      slot: true
    },
    {
      label: '真实姓名',
      prop: 'realName',
      rules: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ]
    },
    {
      label: '手机号',
      prop: 'phone',
      rules: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ]
    },
    {
      label: '邮箱',
      prop: 'email',
      rules: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ]
    },
    {
      label: '管理员类型',
      prop: 'adminType',
      type: 'select',
      dicData: [
        { label: '超级管理员', value: 1 },
        { label: '普通管理员', value: 0 }
      ],
      addDisplay: false,
      editDisplay: false
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      search: true,
      dicData: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 }
      ],
      slot: true
    },
    {
      label: '创建时间',
      prop: 'createTime',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      addDisplay: false,
      editDisplay: false
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      addDisplay: false,
      editDisplay: false
    }
  ]
}

// 数据对象
const data = ref([])
const loading = ref(false)
const page = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 加载数据
const onLoad = async (pagination, params) => {
  try {
    loading.value = true
    const queryParams = {
      pageNum: pagination?.currentPage || page.value.currentPage,
      pageSize: pagination?.pageSize || page.value.pageSize,
      username: params?.username || undefined,
      realName: params?.realName || undefined,
      status: params?.status || undefined
    }
    
    Object.keys(queryParams).forEach(key => 
      queryParams[key] === undefined && delete queryParams[key]
    )
    
    const res = await getAdminPage(queryParams)
    if (res.data.code === 200) {
      data.value = res.data.data.records || []
      page.value = {
        ...page.value,
        total: res.data.data.total || 0,
        currentPage: Number(pagination?.currentPage || page.value.currentPage)
      }
    } else {
      ElMessage.error(res.data.message || '获取管理员列表失败')
    }
  } catch (error) {
    ElMessage.error('获取管理员列表失败')
  } finally {
    loading.value = false
  }
}

// 新增记录
const onSubmit = async (row, done, loading) => {
  try {
    loading(true)
    const res = await addAdmin(row)
    if (res.data.code === 200) {
      ElMessage.success('添加成功')
      done()
      onLoad(page.value)
    } else {
      ElMessage.error(res.data.message || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加失败')
  } finally {
    loading(false)
  }
}

// 更新记录
const onUpdate = async (row, index, done, loading) => {
  try {
    loading(true)
    const res = await updateAdmin(row)
    if (res.data.code === 200) {
      ElMessage.success('更新成功')
      done()
      onLoad(page.value)
    } else {
      ElMessage.error(res.data.message || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新失败')
  } finally {
    loading(false)
  }
}

// 删除记录
const onDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该管理员吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteAdmin(row.id)
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      onLoad(page.value)
      return true
    } else {
      ElMessage.error(res.data.message || '删除失败')
      return false
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
    return false
  }
}

// 更新管理员状态
const updateStatus = async (row) => {
  try {
    const status = row.status === 1 ? 0 : 1
    const statusText = status === 1 ? '启用' : '禁用'
    
    await ElMessageBox.confirm(`确定要${statusText}该管理员吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await updateAdminStatus(row.id, status)
    if (res.data.code === 200) {
      ElMessage.success(`${statusText}成功`)
      onLoad(page.value)
    } else {
      ElMessage.error(res.data.msg || `${statusText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 分页大小改变
const sizeChange = (val) => {
  page.value.pageSize = val
  onLoad(page.value)
}

// 当前页改变
const currentChange = (val) => {
  page.value.currentPage = val
  onLoad(page.value)
}

// 搜索条件改变
const searchChange = (params, done) => {
  onLoad(page.value, params)
  done()
}

// 重置搜索
const searchReset = () => {
  onLoad(page.value)
}
</script>

<style scoped>
.admin-container {
  background-color: var(--white-color);
  padding: var(--main-padding);
  border-radius: var(--border-radius);
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  position: relative;
}

.table-container {
  flex: 1;
  overflow: auto;
  position: relative;
}

:deep(.avue-crud__pagination) {
  position: sticky;
  bottom: 0;
  background-color: var(--white-color);
  margin-top: 16px;
  padding: 16px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

:deep(.avue-crud__menu) {
  background-color: var(--white-color);
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}
</style> 